package fmu.pi.view.controllers;

import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import fmu.pi.business.AplicacaoBusiness;
import fmu.pi.model.bean.Usuario;

public class LoginController extends PaneController implements Initializable  {
	
	private static final int HSQL_LOCK_FILE_ERROR = -451;

	@FXML
	private PasswordField senha;
	
	@FXML
	private Button btnOk;
	
	@FXML
	private Label errorMessage;

	private AplicacaoBusiness bo;
	private Usuario usr;
	
	private boolean baseEmUso = false;
	
	public boolean isBaseEmUso() {
		return baseEmUso;
	}

	
	/**
	 * construtor
	 */
	public LoginController() {
		super();
		
		bo = new AplicacaoBusiness();
		
		try {
			
			usr = bo.obterUsuarioSistema();
		
		} catch (SQLException e) {
			
			if (e.getErrorCode() == HSQL_LOCK_FILE_ERROR) {
				baseEmUso = true;
			}
			
			e.printStackTrace();
		}
		
	}

	@FXML
	public void procescsLogin(ActionEvent event) {
		verifcaSenha();
	}

	private void verifcaSenha() {
		
		if (senha.getText().equals(usr.getSenha())) {
			main.renderizeMainForm();
		} else {
			errorMessage.setText("Senha Inválida!");
		}
			
	}

	public void processKey(KeyEvent keyEvent){
		if (keyEvent.getCode() == KeyCode.ENTER) {
			verifcaSenha();
		}
	}
	
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		senha.setText("senha");
		errorMessage.setText("");
	}
}
